﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;

namespace RuyeeModbus
{

    [Serializable]
    public abstract class ExceptionArgs
    {
        /// <summary>The string message associated with this exception.</summary>
        public virtual String Message { get { return String.Empty; } }
    }
    /// <summary>Represents errors that occur during application execution.</summary>
    /// <typeparam name="TExceptionArgs">The type of exception and any additional arguments associated with it.</typeparam>
    [Serializable]
    public sealed class Exception<TExceptionArgs> : Exception, ISerializable where TExceptionArgs : ExceptionArgs
    {
        private const String c_args = "Args";     // For (de)serialization
        private readonly TExceptionArgs m_args;

        /// <summary>Returns a reference to this exception's additional arguments.</summary>
        public TExceptionArgs Args { get { return m_args; } }

        /// <summary>
        /// Initializes a new instance of the Exception class with a specified error message 
        /// and a reference to the inner exception that is the cause of this exception. 
        /// </summary>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        /// <param name="innerException">The exception that is the cause of the current exception, 
        /// or a null reference if no inner exception is specified.</param>
        public Exception(String message = null, Exception innerException = null)
            : this(null, message, innerException) { }

        // The fourth public constructor because there is a field
        /// <summary>
        /// Initializes a new instance of the Exception class with additional arguments, 
        /// a specified error message, and a reference to the inner exception 
        /// that is the cause of this exception. 
        /// </summary>
        /// <param name="args">The exception's additional arguments.</param>
        /// <param name="message">The error message that explains the reason for the exception.</param>
        /// <param name="innerException">The exception that is the cause of the current exception, 
        /// or a null reference if no inner exception is specified.</param>
        public Exception(TExceptionArgs args, String message = null, Exception innerException = null)
            : base(message, innerException)
        {
            m_args = args;
        }

        // Because at least 1 field is defined, define the special deserialization constructor
        // Since this class is sealed, this constructor is private
        // If this class were not sealed, this constructor should be protected
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        private Exception(SerializationInfo info, StreamingContext context)
            : base(info, context)
        { // Let the base deserialize its fields
            m_args = (TExceptionArgs)info.GetValue(c_args, typeof(TExceptionArgs));
        }

        // Because at least 1 field is defined, define the serialization method
        /// <summary>
        /// When overridden in a derived class, sets the SerializationInfo with information about the exception.
        /// </summary>
        /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param>
        /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param>
        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue(c_args, m_args);
            base.GetObjectData(info, context);
        }

        /// <summary>Gets a message that describes the current exception.</summary>
        public override String Message
        {
            get
            {
                String baseMsg = base.Message;
                return (m_args == null) ? baseMsg : baseMsg + " (" + m_args.Message + ")";
            }
        }

        /// <summary>
        /// Determines whether the specified Object is equal to the current Object.
        /// </summary>
        /// <param name="obj">The Object to compare with the current Object. </param>
        /// <returns>true if the specified Object is equal to the current Object; otherwise, false.</returns>
        public override Boolean Equals(Object obj)
        {
            Exception<TExceptionArgs> other = obj as Exception<TExceptionArgs>;
            if (obj == null) return false;
            return Object.Equals(m_args, other.m_args) && base.Equals(obj);
        }
        public override int GetHashCode() { return base.GetHashCode(); }
    }

    [Serializable]
    public sealed class ModbusException : ExceptionArgs
    {
        private readonly ModbusExceptionCode _ExceptionCode;

        public ModbusExceptionCode ExceptionCode
        {
            get { return _ExceptionCode; }

        }
        public ModbusException(ModbusExceptionCode exceptionCode)
        {
            _ExceptionCode = exceptionCode;
        }
        public override string Message
        {
            get
            {
                if (_ExceptionCode == null)
                {
                    return base.Message;
                }
                else
                {
                    switch (_ExceptionCode)
                    {
                        case ModbusExceptionCode.IllegalFunction:
                            {
                                return "ExceptionCode[" + ModbusExceptionCode.IllegalFunction.ToString() + "]IllegalFunction";
                            }
                        case ModbusExceptionCode.IllegalDataAddress:
                            {
                                return "ExceptionCode[" + ModbusExceptionCode.IllegalDataAddress.ToString() + "]IllegalDataAddress";
                            }
                        case ModbusExceptionCode.IllegalDataValue:
                            {
                                return "ExceptionCode[" + ModbusExceptionCode.IllegalDataValue.ToString() + "]IllegalDataValue";
                            }

                        case ModbusExceptionCode.SlaveDeviceFalure:
                            {
                                return "ExceptionCode[" + ModbusExceptionCode.SlaveDeviceFalure.ToString() + "]SlaveDeviceFalure";
                            }
                        case ModbusExceptionCode.Acknowledge:
                            {
                                return "ExceptionCode[" + ModbusExceptionCode.Acknowledge.ToString() + "]Acknowledge";
                            }

                        case ModbusExceptionCode.SlaveDeviceBusy:
                            {
                                return "ExceptionCode[" + ModbusExceptionCode.SlaveDeviceBusy.ToString() + "]SlaveDeviceBusy";
                            }
                        case ModbusExceptionCode.MemoryPartiyError:
                            {
                                return "ExceptionCode[" + ModbusExceptionCode.MemoryPartiyError.ToString() + "]MemoryPartiyError";
                            }
                        case ModbusExceptionCode.GatewayPathUnavailable:
                            {
                                return "ExceptionCode[" + ModbusExceptionCode.GatewayPathUnavailable.ToString() + "]GatewayPathUnavailable";
                            }
                        case ModbusExceptionCode.GatewayTargetDeviceFailedToRespond:
                            {
                                return "ExceptionCode[" + ModbusExceptionCode.GatewayTargetDeviceFailedToRespond.ToString() + "]GatewayTargetDeviceFailedToRespond";
                            }
                        default:
                            {
                                return base.Message;
                            }
                    }
                }
            }
        }
    }
}
